﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Vita.Entities;
using Vita.Entities.Services;

namespace Vita.Modules.Calendar {
  public class CalendarModule : EntityModule, ICalendarService {
    public static readonly Version CurrentVersion = new Version("1.0.0.0");

    ITimerService _timers;
    object _lock = new object(); 

    public CalendarModule(EntityArea area) : base(area, "CalendarModule", version: CurrentVersion) {
      RegisterEntities(typeof(ICalendar), typeof(ICalendarEvent), typeof(ICalendarEventSchedule));
      this.App.RegisterService<ICalendarService>(this); 
    }
    public override void Init() {
      base.Init();
      _timers = App.GetService<ITimerService>();
      _timers.Elapsed10Seconds += Timers_Elapsed10Seconds;
      _timers.Elapsed1Minute += Timers_Elapsed1Minute;
      var evtSchedEnt = App.Model.GetEntityInfo(typeof(ICalendarEventSchedule));
      evtSchedEnt.SaveEvents.SavingChanges += EventSchedule_SavingChanges;
    }

    void EventSchedule_SavingChanges(Entities.Runtime.EntityRecord record, EventArgs args) {
      var ent = (ICalendarEventSchedule)record.EntityInstance;
      ent.ProjectedNextOn = null; // ent.CalculateNextProjected(null);
    }

    void Timers_Elapsed1Minute(object sender, EventArgs e) {
      
    }

    void Timers_Elapsed10Seconds(object sender, EventArgs e) {

    }

    #region ICalendarService members

    public void ScheduleEvent() {

    }

    public void RegisterEventHandler(Guid? calendarId, string eventName, Action<ICalendarEvent> handler) {

    }

    public event EventHandler<CalendarEventArgs> EventStarting;


    public void OnEventStarting() {
      if (EventStarting != null)
        EventStarting(this, new CalendarEventArgs()); 
    }
    #endregion

    #region Action handlers
    class CalendarEventHandler {
      public string Key;
      public Action<ICalendarEvent> Action;
    }

    public void AddEventHandler(string key, Action<ICalendarEvent> action) {

    }
    Dictionary<string, CalendarEventHandler> _eventHandlers = 
        new Dictionary<string, CalendarEventHandler>(StringComparer.InvariantCultureIgnoreCase);

    string GetHandlerKey(Guid? calendarId, string eventName) {
      if (calendarId == null || calendarId.Value == Guid.Empty)
        return eventName;
      return calendarId + "/" + eventName;
    }

    Action<ICalendarEvent> GetEventHandler(Guid? calendarId, string eventName) {
      var key = GetHandlerKey(calendarId, eventName); 
      CalendarEventHandler handler;
      if (_eventHandlers.TryGetValue(key, out handler))
        return handler.Action;
      return null; 
    }

    #endregion
  }//class
}//ns
